from rest_framework import filters
from rest_framework.exceptions import ValidationError


# class DateRangeFilter(filters.BaseFilterBackend):
#     def filter_queryset(self, request, queryset, view):
#         query = queryset
#         params = request.query_params
#
#         if 'start_date' in params and 'end_date' not in params:
#             start_date = params['start_date']
#             query = query.filter(start_date__date=start_date)
#
#         elif 'start_date' in params and 'end_date' in params:
#             start_date = params['start_date']
#             end_date = params['end_date']
#
#             if start_date > end_date:
#                 raise ValidationError(
#                     'Start date must be lower than end date.')
#
#             query = query.filter(start_date__date__range=[start_date, end_date])
#
#         return query


def date_range_filter_queryset(request, queryset):
    query = queryset
    params = request.query_params

    if 'start_date' in params and 'end_date' not in params:
        start_date = params['start_date']
        query = query.filter(start_date__date=start_date)

    elif 'start_date' in params and 'end_date' in params:
        start_date = params['start_date']
        end_date = params['end_date']

        if start_date > end_date:
            raise ValidationError(
                'Start date must be lower than end date.')
        query = query.filter(start_date__date__range=[start_date, end_date])
        if query.count() == 0:
            # If no results, perform another query
            query = query.filter(start_date__date__range=[start_date, end_date])

    return query